package com.ocr.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.ocr.MainActivity;
import com.ocr.R;
import com.ocr.entities.HistoryItem;
import com.ocr.utils.ApplicationConstant;
import com.ocr.utils.CropOption;
import com.ocr.utils.CropOptionAdapter;
import com.ocr.utils.OCRAsyntask;

import eu.janmuller.android.simplecropimage.CropImage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentScan extends Fragment {
	private RelativeLayout layoutEditImage; // layout edit img show when have
											// img
	public static Button btnSelectImg;
	private RelativeLayout layoutAd;// layout admod
	private LinearLayout layoutNoSelectImg;// layout no select img
	private ImageView imageViewSeleted;
	public static Button btnCrop;
	public static Button btnRotate;
	public static Button btnScan;
	private Bitmap imgSeleted;
	private TessBaseAPI tessBaseAPI = new TessBaseAPI();
	private MainActivity mainActivity;
	private String imgpath;// path of selected img
	private AlertDialog.Builder dialogChooseImg;
	private Uri uriImage;// uri cua image sau khi chon
	public static final String DATA_PATH = Environment
			.getExternalStorageDirectory().toString() + "/OCR/";
	// status
	public static LinearLayout layoutStatus;
	public static TextView lblStatus;// lbl status when scan

	// string resource
	public static void disableAllView() {
		btnCrop.setEnabled(false);
		btnRotate.setEnabled(false);
		btnScan.setEnabled(false);
		btnSelectImg.setEnabled(false);
	}

	public static void enableAllView() {
		btnCrop.setEnabled(true);
		btnRotate.setEnabled(true);
		btnScan.setEnabled(true);
		btnSelectImg.setEnabled(true);
	}

	private Handler handlerAfterScan = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			enableAllView();
			// imageViewSeleted.setImageBitmap(OCRAsyntask.bitmapTest);
			// reset img
			imgSeleted = null;
			String result = (String) msg.obj;
			if (result == null || result.trim().length() == 0) {
				layoutStatus.setVisibility(View.GONE);
				AnimationDrawable btnAnimation = (AnimationDrawable) btnScan.getBackground();
				btnAnimation.stop();
				enableAllView();
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						getActivity());
				alertDialogBuilder
						.setMessage(R.string.ocr_not_recognize)
						.setCancelable(true)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
									}
								});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			} else {
				Date date = new Date();
				HistoryItem historyItem = new HistoryItem(date, imgpath, result);
				mainActivity.HISTORYDAO.add(historyItem);
				mainActivity.navigateToFragmentResult(result);
			}

		}
	};
	private Handler handleWhileProcessImg = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// reset img
			String message = (String) msg.obj;
			lblStatus.setText(message);
		}
	};

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		this.mainActivity = (MainActivity) activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		final View root = inflater.inflate(R.layout.fragment_scan, container,
				false);
		layoutStatus = (LinearLayout) root.findViewById(R.id.layout_status);
		layoutAd = (RelativeLayout) root.findViewById(R.id.layout_admod);
		lblStatus = (TextView) root.findViewById(R.id.lbl_status);
		layoutEditImage = (RelativeLayout) root
				.findViewById(R.id.layout_edit_image);
		btnSelectImg = (Button) root.findViewById(R.id.btn_add_img);
		layoutNoSelectImg = (LinearLayout) root
				.findViewById(R.id.layout_img_not_selected);
		imageViewSeleted = (ImageView) root.findViewById(R.id.img_selected);
		btnRotate = (Button) root.findViewById(R.id.btn_rotate);
		btnScan = (Button) root.findViewById(R.id.btn_scan);
		btnCrop = (Button) root.findViewById(R.id.btn_crop);
		// create ad
		// AdView adView = new AdView(getActivity());
		// adView.setAdSize(AdSize.BANNER);
		// adView.setAdUnitId(ApplicationConstant.AD_ID);
		// layoutAd.addView(adView);
		// com.google.android.gms.ads.AdRequest adRequest = new
		// com.google.android.gms.ads.AdRequest.Builder().build();
		// adView.loadAd(adRequest);
		AdView mAdView = (AdView) root.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		mAdView.loadAd(adRequest);
		// dialog choose image
		dialogChooseImg = new AlertDialog.Builder(getActivity());
		dialogChooseImg.setMessage(root.getResources().getString(
				R.string.content_dialog_choose_picture));
		dialogChooseImg.setPositiveButton("Gallery",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						Intent pictureActionIntent = new Intent(
								Intent.ACTION_GET_CONTENT, null);
						pictureActionIntent.setType("image/*");
						pictureActionIntent.putExtra("return-data", true);
						startActivityForResult(
								pictureActionIntent,
								ApplicationConstant.REQUEST_SELECT_IMG_FORM_GALLERY);
					}
				});

		dialogChooseImg.setNegativeButton("Camera",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						Intent pictureActionIntent = new Intent(
								android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(
								pictureActionIntent,
								ApplicationConstant.REQUEST_SELECT_IMG_FORM_CAMERA);

					}
				});
		// action listener
		btnSelectImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Log.d("---fragment scan:", "btnSelectImg.setOnClickListener");
				dialogChooseImg.show();
			}
		});
		btnCrop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (imgSeleted != null) {
					cropImg();
				} else
					Toast.makeText(getActivity(), "Please select an image!",
							Toast.LENGTH_SHORT).show();
			}
		});
		btnRotate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (imgSeleted != null) {
					int width = imgSeleted.getWidth();
					int height = imgSeleted.getHeight();
					Matrix matrix = new Matrix();
					matrix.postRotate(90);
					Bitmap scaledBitmap = Bitmap.createScaledBitmap(imgSeleted,
							width, height, true);
					Bitmap rotateBitMap = Bitmap.createBitmap(scaledBitmap, 0,
							0, scaledBitmap.getWidth(),
							scaledBitmap.getHeight(), matrix, true);
					imgSeleted = rotateBitMap;
					imageViewSeleted.setImageBitmap(imgSeleted);
				} else
					Toast.makeText(
							getActivity(),
							root.getResources().getString(
									R.string.toast_img_noselect),
							Toast.LENGTH_SHORT).show();
			}
		});
		final AnimationDrawable btnAnimation = (AnimationDrawable) btnScan
				.getBackground();
		btnScan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (imgSeleted != null) {
					btnAnimation.start();
					final OCRAsyntask ocrAsyntask = new OCRAsyntask(
							getActivity(), handlerAfterScan, tessBaseAPI,
							DATA_PATH, handleWhileProcessImg);
					ocrAsyntask.execute(imgSeleted);
					// time out after 70s
					Handler handlerTimeout = new Handler();
					handlerTimeout.postDelayed(new Runnable() {
						@Override
						public void run() {
							if (ocrAsyntask.getStatus() == AsyncTask.Status.RUNNING) {
								ocrAsyntask.cancel(true);
								layoutStatus.setVisibility(View.GONE);
								btnAnimation.stop();
								enableAllView();
								AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
										getActivity());
								alertDialogBuilder
										.setMessage(R.string.ocr_not_recognize)
										.setCancelable(true)
										.setPositiveButton(
												"OK",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int id) {
													}
												});
								AlertDialog alertDialog = alertDialogBuilder
										.create();
								alertDialog.show();
							}
						}
					}, 70000);
				} else
					Toast.makeText(
							getActivity(),
							root.getResources().getString(
									R.string.toast_img_noselect),
							Toast.LENGTH_SHORT).show();
			}
		});
		return root;

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ApplicationConstant.REQUEST_SELECT_IMG_FORM_CAMERA
				|| requestCode == ApplicationConstant.REQUEST_SELECT_IMG_FORM_GALLERY) {
			if (data != null) {
				uriImage = data.getData();
				imgSeleted = getBitmapFromCameraData(data, getActivity());
				// dialogCrop.show();
				layoutNoSelectImg.setVisibility(View.GONE);
				imageViewSeleted.setImageBitmap(imgSeleted);
				imageViewSeleted.setVisibility(View.VISIBLE);
				layoutEditImage.setVisibility(View.VISIBLE);
				layoutAd.setVisibility(View.GONE);
			}
		} else if (requestCode == ApplicationConstant.REQUEST_CROP_IMAGE) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				imgSeleted = extras.getParcelable("data");
				imageViewSeleted.setImageBitmap(imgSeleted);
			}
			File f = new File(uriImage.getPath());
			if (f.exists())
				f.delete();
		}
	}

	public Bitmap getBitmapFromCameraData(Intent data, Context context) {
		Uri selectedImage = data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(selectedImage,
				filePathColumn, null, null, null);
		cursor.moveToFirst();
		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		imgpath = cursor.getString(columnIndex);
		cursor.close();
		return BitmapFactory.decodeFile(imgpath);
	}

	public void cropImg() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getActivity().getPackageManager()
				.queryIntentActivities(intent, 0);

		int size = list.size();

		if (size == 0) {
			return;
		} else {
			intent.setData(this.uriImage);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			// intent.putExtra("aspectX", 1);
			// intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i,
						ApplicationConstant.REQUEST_CROP_IMAGE);
			} else {
				for (ResolveInfo res : list) {
					final CropOption co = new CropOption();

					co.title = getActivity().getPackageManager()
							.getApplicationLabel(
									res.activityInfo.applicationInfo);
					co.icon = getActivity().getPackageManager()
							.getApplicationIcon(
									res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(co);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(
						getActivity(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										ApplicationConstant.REQUEST_CROP_IMAGE);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {

						if (uriImage != null) {
							getActivity().getContentResolver().delete(uriImage,
									null, null);
							uriImage = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}
}
